<template>
    <Breadcrumb :bread-crumb-list="breadCrumbList" />
    <div class="zqy-seach-table data-layer">
        <div class="zqy-table-top">
            <div class="btn-container">
                <el-button
                    type="primary"
                    @click="addData"
                    :disabled="isMaxLevel"
                >
                  新建目录
                </el-button>
            </div>
            <div class="zqy-seach">
                <el-radio-group v-model="tableType" @change="changeTypeEvent">
                    <el-radio-button label="layer">分层搜索</el-radio-button>
                    <el-radio-button label="all">全局搜索</el-radio-button>
                </el-radio-group>
                <el-input
                    v-model="keyword"
                    placeholder="请输入搜索条件 回车进行搜索"
                    :maxlength="200"
                    clearable
                    @input="inputEvent"
                    @keyup.enter="handleCurrentChange(1)"
                />
            </div>
        </div>
        <LoadingPage :visible="loading" :network-error="networkError" @loading-refresh="initData(false)">
            <div class="zqy-table">
                <BlockTable
                    :table-config="tableConfig"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                >
                    <template #nameSlot="scopeSlot">
                        <span
                            v-if="tableType === 'layer'"
                            class="name-click"
                            @click="showDetail(scopeSlot.row)"
                        >{{ scopeSlot.row.catalog_name }}</span>
                        <span v-else>{{ scopeSlot.row.name }}</span>
                    </template>
                    <template #parentNameSlot="scopeSlot">
                        <span
                            v-if="tableType === 'layer' && scopeSlot.row.parentNameList"
                            class="name-click"
                            @click="showParentDetail(scopeSlot.row)"
                        >{{ scopeSlot.row.parentNameList }}</span>
                        <span v-else>{{ scopeSlot.row.parentNameList ?? '-' }}</span>
                    </template>
                    <template #options="scopeSlot">
                        <div class="btn-group btn-group-msg">
                            <el-dropdown trigger="click">
                                <span class="click-show-more">更多</span>
                                <template #dropdown>
                                    <el-dropdown-menu>
                                        <el-dropdown-item @click="editData(scopeSlot.row)">编辑</el-dropdown-item>
                                        <el-dropdown-item @click="deleteData(scopeSlot.row)">删除</el-dropdown-item>
                                        <el-dropdown-item @click="layerAreaView(scopeSlot.row)">子目录</el-dropdown-item>
                                    </el-dropdown-menu>
                                </template>
                            </el-dropdown>
                        </div>
                    </template>
                </BlockTable>
                <el-button class="back-up" @click="showParentDetail" v-if="parentLayerId">
                    返回上一分层
                </el-button>
            </div>
        </LoadingPage>
        <AddModal ref="addModalRef" />
        <DataModelDetail ref="dataModelDetailRef"></DataModelDetail>
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref, computed, onMounted } from 'vue'
import Breadcrumb from '@/layout/bread-crumb/index.vue'
import LoadingPage from '@/components/loading/index.vue'
import AddModal from './add-modal/index.vue'
import DataModelDetail from './layer-area/data-model-detail/index.vue'
import { BreadCrumbList, TableConfig } from './list.config'
import {
  GetCatalogTree,
  CreateCatalog,
  UpdateCatalog,
  DeleteCatalog,
  GetCatalogDetail
} from '@/services/data-catalog.service'
import { GetParentLayerNode } from '@/services/data-layer.service' // 保留这个，后面可能用
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()
const BreadCrumbList = [
  {
    name: '数据资源目录',
    code: 'data-catalog'
  }
]
const breadCrumbList = reactive(BreadCrumbList)
const tableConfig: any = reactive(TableConfig)
const keyword = ref('')
const loading = ref(false)
const networkError = ref(false)
const addModalRef = ref<any>(null)
const tableType = ref<string>('layer')
const parentLayerId = ref<string>('')
const parentIdStack = ref<number[]>([])
const currentLevelInfo = ref<any>(null)
// 计算当前是否已达到最大层级
const isMaxLevel = computed(() => {
  if (!parentLayerId.value) return false  // 根目录可以创建
  if (!currentLevelInfo.value) return false
  return currentLevelInfo.value.level >= 3  // level=3（数据集）不能再创建子目录
})
const dataModelDetailRef = ref<any>(null)

function initData(tableLoading?: boolean) {
  loading.value = tableLoading ? false : true
  networkError.value = networkError.value || false

  // 如果有父级ID，获取当前层级信息
  if (parentLayerId.value) {
    GetCatalogDetail(parentLayerId.value).then((res: any) => {
      if (res.success && res.data) {
        currentLevelInfo.value = res.data
      }
    }).catch(() => {
      currentLevelInfo.value = null
    })
  } else {
    currentLevelInfo.value = null
  }

  // 调用新接口
  GetCatalogTree({
    parent_id: parentLayerId.value || undefined,
    include_inactive: false
  }).then((res: any) => {
    if (res.success) {
      tableConfig.tableData = res.data || []
      tableConfig.pagination.total = res.data?.length || 0
    }
    loading.value = false
    tableConfig.loading = false
    networkError.value = false

    if (route.query && route.query.parentLayerId) {
      router.replace({
        name: 'data-layer'
      })
    }
  }).catch(() => {
    tableConfig.tableData = []
    tableConfig.pagination.total = 0
    loading.value = false
    tableConfig.loading = false
    networkError.value = true
  })
}

function changeTypeEvent(e: string) {
    parentLayerId.value = null
    tableConfig.pagination.currentPage = 1
    tableConfig.pagination.pageSize = 10

    tableConfig.tableData = []
    tableConfig.pagination.total = 0
    initData()
}

function addData() {
  addModalRef.value.showModal((data: any) => {
    return new Promise((resolve: any, reject: any) => {
      // 数据已经在弹窗中格式化好了，直接使用
      CreateCatalog(data).then((res: any) => {
        if (res.success) {
          ElMessage.success(res.message || '创建成功')
          initData()
          resolve()
        } else {
          ElMessage.error(res.message || '创建失败')
          reject()
        }
      }).catch((error: any) => {
        ElMessage.error('创建失败')
        reject(error)
      })
    })
  }, null, parentLayerId.value)
}
function editData(data: any) {
  addModalRef.value.showModal((updateData: any) => {
    return new Promise((resolve: any, reject: any) => {
      // 从updateData中提取id，其他数据已经格式化好了
      const catalogId = updateData.id
      delete updateData.id  // 删除id，因为UpdateCatalog的id是路径参数

      UpdateCatalog(catalogId, updateData).then((res: any) => {
        if (res.success) {
          ElMessage.success(res.message || '更新成功')
          initData()
          resolve()
        } else {
          ElMessage.error(res.message || '更新失败')
          reject()
        }
      }).catch((error: any) => {
        ElMessage.error('更新失败')
        reject(error)
      })
    })
  }, data)
}

// 删除
function deleteData(data: any) {
  ElMessageBox.confirm('确定删除该目录吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    DeleteCatalog(data.id, false).then((res: any) => {
      if (res.success) {
        ElMessage.success(res.message || '删除成功')
        initData()
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    }).catch(() => {
      ElMessage.error('删除失败')
    })
  })
}

// 跳转分层数据模型
function dataModelPage(data: any) {
    dataModelDetailRef.value.showModal(data)
}

// 跳转分层领域
function layerAreaView(data: any) {
    GetParentLayerNode({
        id: data.id
    }).then((res: any) => {
        router.push({
            name: 'layer-area',
            query: {
                id: data.id,
                parentLayerId: res.data.parentLayerId,
                tableType: tableType.value
            }
        })
    }).catch((error: any) => {
        console.error('获取父级节点失败', error)
    })
}

function inputEvent(e: string) {
    if (e === '') {
        handleCurrentChange(1)
    }
}

// 跳转子集分层
function showDetail(data: any) {
  // 如果是数据集（level=3），跳转到数据资产页面
  if (data.level === 3) {
    ElMessageBox.confirm(
        '数据集是最后一层目录，是否前往数据资产模块查看该数据集下的表？',
        '提示',
        {
          confirmButtonText: '前往数据资产',
          cancelButtonText: '取消',
          type: 'info'
        }
    ).then(() => {
      router.push({
        name: 'data-asset',
        query: {
          catalog_id: data.id,
          catalog_name: data.catalog_name
        }
      })
    }).catch(() => {
      // 用户点击取消，不做任何操作
    })
    return
  }

  // 否则进入子目录
  if (parentLayerId.value) {
    parentIdStack.value.push(Number(parentLayerId.value))
  } else {
    parentIdStack.value.push(0)
  }

  parentLayerId.value = data.id
  tableConfig.pagination.currentPage = 1
  tableConfig.pagination.pageSize = 10
  initData()
}

// 跳转父级分层
function showParentDetail() {
  if (parentIdStack.value.length === 0 && !parentLayerId.value) {
    ElMessage.warning('已经是顶级目录了')
    return
  }

  if (parentIdStack.value.length === 0) {
    // 回到根目录
    parentLayerId.value = null
  } else {
    // 从栈中弹出父级ID
    const parentId = parentIdStack.value.pop()
    parentLayerId.value = parentId === 0 ? null : String(parentId)
  }

  tableConfig.pagination.currentPage = 1
  tableConfig.pagination.pageSize = 10
  initData()
}

function handleSizeChange(e: number) {
    tableConfig.pagination.pageSize = e
    initData()
}

function handleCurrentChange(e: number) {
    tableConfig.pagination.currentPage = e
    initData()
}

onMounted(() => {

    if (route.query && (route.query.parentLayerId || route.query.tableType)) {
        tableType.value = route.query.tableType ?? 'layer'
        parentLayerId.value = route.query.parentLayerId ?? null
    }

    tableConfig.pagination.currentPage = 1
    tableConfig.pagination.pageSize = 10
    initData()
})
</script>

<style lang="scss">
.data-layer {
    &.zqy-seach-table {
        .zqy-table-top {
            .btn-container {
                height: 100%;
                display: flex;
                align-items: center;
            }
            .zqy-seach {
                display: flex;
                align-items: center;
                .el-radio-group {
                    margin-right: 8px;
                    .el-radio-button__inner {
                        font-size: getCssVar('font-size', 'extra-small');
                    }
                }
            }
        }
        .zqy-table {
            position: relative;
            .btn-group-msg {
                justify-content: space-around;
            }
            .back-up {
                position: absolute;
                bottom: 22px;
                left: 20px;
            }
        }
    }
}
</style>